package cn.toma.controller;

import cn.toma.common.exception.RedisConnectException;
import cn.toma.common.utils.StringUtils;
import cn.toma.common.utils.web.CookieUtils;
import cn.toma.core.annotation.AuthToken;
import cn.toma.core.exception.GlobalException;
import cn.toma.core.result.BaseApi;
import cn.toma.core.result.CodeMsg;
import cn.toma.core.result.Result;
import cn.toma.wx.vo.OnlineUserVo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zqx
 * @version 1.0.0
 * @ClassName CaptchaApi.java
 * @Description
 * @createTime 2019年09月23日 09:17:00
 */
@Api(value = "图形验证码", tags = "图形验证码")
@Controller
@RequestMapping("/captcha")
public class CaptchaApi extends BaseApi
{
	private static String COOKIE_NAME = "API_CAPTCHA_CODE";

	@Autowired
	private Producer producer;

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;


	/**
	 * 生成验证码
	 */
	@ApiOperation("获取验证图形验证码")
	@GetMapping
	public void index(HttpServletRequest request, HttpServletResponse response) throws RedisConnectException
	{
		HttpSession session = request.getSession();

		response.setDateHeader("Expires", 0);

		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");

		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");

		// return a jpeg
		response.setContentType("image/jpeg");

		String uuid = UUID.randomUUID().toString();
		// 将验证码key，及验证码的图片返回
		// 新增到Cookie
		Cookie cookie = new Cookie(COOKIE_NAME, uuid);
		response.addCookie(cookie);

		// create the text for the image
		String capText = producer.createText();

		// store the text in the session
		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

		// 将验证码以<key,value>形式缓存到redis
		long CAPTCHA_EXPIRES = 5 * 60;
		redisTemplate.opsForValue().set("IMG_CODE:" + uuid, capText, CAPTCHA_EXPIRES, TimeUnit.SECONDS);

		// create the image with the text
		BufferedImage bi = producer.createImage(capText);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// write the data out
		try {
			ImageIO.write(bi, "jpg", out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 验证图形验证码
	 *
	 * @param request
	 * @param code    输入的验证码
	 * @return
	 */
	@ApiOperation("验证图形验证码注意需要携带Cookie  此接口仅做测试用 ")
	@ApiImplicitParam(paramType = "query", name = "code", value = "图形验证码", required = true, dataType = "String")
	@GetMapping("/check")
	@ResponseBody
	public Result checkCode(HttpServletRequest request, @NotNull(message = "{required}") String code) throws GlobalException
	{
		try {
			boolean checkImgCode = checkImgCode(code, request);
			if (checkImgCode) {
				return getSuccessObj();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return getFailedObj();
		}
		return getFailedObj(CodeMsg.IMG_CODE_FAIL);
	}


	/*@ApiOperation(value = "发送验证码",notes = "1.获取图形验证码 2.注意提交cookie")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "phone", value = "如果不填写将发送已经绑定的手机号", required = false, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "imgCode", value = "图形验证码 如果不填写Phoen 那么可不填此参数",required = false, dataType = "String")
	})
	@AuthToken
	@GetMapping("/sms/send")
	@ResponseBody
	public Result sendSms(String phone, String imgCode, HttpServletRequest request)
	{
		try {
			if (StringUtils.isNotEmpty(phone)) {
				if (!StringUtils.checkPhone(phone)) {
					return getFailedObj(CodeMsg.PHONE_FORMAT_FAIL);
				}
				if (StringUtils.isEmpty(imgCode)) {
					return getFailedObj(CodeMsg.IMG_CODE_NULL);
				}
				// 验证图形码
				boolean checkImgCode = checkImgCode(imgCode, request);
				if (!checkImgCode) {
					return getFailedObj(CodeMsg.IMG_CODE_FAIL);
				}
			}
			else {
				OnlineUserVo onlineUserVo = getOnlineUser(request);
				CargoMan cargoMan = onlineUserVo.getCargoMan();
				phone = cargoMan.getPhone();
				if (StringUtils.isEmpty(phone)) {
					return getFailedObj(CodeMsg.PHONE_NULL);
				}
			}
			String validCode = StringUtils.getValidCode(6);
			boolean sendVerifySms = smsComponent.sendVerifySms(validCode, phone);
			if (sendVerifySms) {
				redisTemplate.opsForValue().set("SMS_CODE:" + phone, validCode, 10, TimeUnit.MINUTES);
				return getSuccessObj();
			}
		} catch (Exception e) {
			return getFailedObj();
		}
		return getFailedObj(CodeMsg.FAIL);
	}*/


	/**
	 * 私有方法 验证图形验证码
	 * @param imgCode 验证码
	 * @param request 带有cookie
	 * @return
	 */
	private boolean checkImgCode(String imgCode, HttpServletRequest request)
	{
		boolean flag = false;
		String cookieValue = CookieUtils.getCookieValue(request, COOKIE_NAME);
		if (StringUtils.isNotEmpty(imgCode) || StringUtils.isNotEmpty(cookieValue)) {
			Boolean aBoolean = redisTemplate.hasKey("IMG_CODE:" + cookieValue);
			if (aBoolean) {
				String redisCode = (String) redisTemplate.opsForValue().get("IMG_CODE:" + cookieValue);
				if (StringUtils.isNotEmpty(redisCode)) {
					if (imgCode.equals(redisCode)){
						redisTemplate.delete("IMG_CODE:" + cookieValue);
						flag = true;
					}
				}
			}
		}
		return flag;
	}

}
